package com.hex.ds.hdtp.core.app.script.test.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrSpliter;
import com.hex.ds.hdtp.core.app.common.enums.DataTransferTypeEnum;
import com.hex.ds.hdtp.core.app.data.table.dto.response.TableTransferListResponseDto;
import com.hex.ds.hdtp.core.app.data.table.service.ITableTransferListService;
import com.hex.ds.hdtp.core.app.data.transfer.dto.request.DataTransferListRequestDto;
import com.hex.ds.hdtp.core.app.data.transfer.dto.request.DataTransferTaskRequestDto;
import com.hex.ds.hdtp.core.app.data.transfer.service.IDataTransferTaskService;
import com.hex.ds.hdtp.core.app.metadata.service.ISourceInfoService;
import com.hex.ds.hdtp.core.app.script.test.converter.IScriptTestDataAnalysisConverter;
import com.hex.ds.hdtp.core.app.script.test.dto.request.ScriptTestDataAnalysisRequestDto;
import com.hex.ds.hdtp.core.app.script.test.dto.response.ScriptDataTestListResponseDto;
import com.hex.ds.hdtp.core.app.script.test.dto.response.ScriptDataTestTaskResponseDto;
import com.hex.ds.hdtp.core.app.script.test.dto.response.ScriptTestDataAnalysisResponseDto;
import com.hex.ds.hdtp.core.app.script.test.enums.ScriptDataAnalysisResultEnum;
import com.hex.ds.hdtp.core.app.script.test.service.IScriptDataTestListService;
import com.hex.ds.hdtp.core.app.script.test.service.IScriptDataTestSyncService;
import com.hex.ds.hdtp.core.app.script.test.service.IScriptDataTestTaskService;
import com.hex.ds.hdtp.core.app.script.test.service.IScriptTestDataAnalysisService;
import com.hex.ds.hdtp.core.app.script.transfer.dto.response.ScriptConvertTargetListResponseDto;
import com.hex.ds.hdtp.core.app.script.transfer.service.IScriptConvertTargetListService;
import com.hex.ds.hdtp.core.inf.metadata.po.SourceInfoPo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Package com.hex.ds.hdtp.core.app.script.test.service.impl
 * @ClassName ScriptDataTestSyncService
 * @Description 脚本测试-数据同步（对齐）
 * @Author jian.qiao
 * @Date 2023/10/27 18:37
 * @Version v1.0
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ScriptDataTestSyncService implements IScriptDataTestSyncService {

    private final IScriptTestDataAnalysisService dataAnalysisService;
    private final IScriptConvertTargetListService convertTargetListService;
    private final IScriptDataTestListService dataTestListService;
    private final IScriptDataTestTaskService dataTestTaskService;
    private final ISourceInfoService sourceInfoService;
    private final ITableTransferListService tableTransferListService;
    private final IDataTransferTaskService dataTransferTaskService;
    private final IScriptTestDataAnalysisConverter scriptTestDataAnalysisConverter;

    /**
     * @Method dataSync <br>
     * @Param
     * @Param pkId <br>
     * @Return void <br>
     * @Description 数据同步（对齐）<br>
     * @Author jian.qiao<br>
     * @Date 2023/10/27 18:35 <br>
     * @Version V1.0<br>
     */
    @Override
    public void dataSync(String pkId) {
        try {
            ScriptDataTestTaskResponseDto testTaskResponseDto = dataTestTaskService.queryById(pkId);
            List<ScriptTestDataAnalysisResponseDto>  list = dataAnalysisService.queryList(buildDataAnalysisRequestDto(pkId));
            //构建对象，添加数据迁移任务
            for (ScriptTestDataAnalysisResponseDto responseDto : list) {
                String transferTaskPkId = dataTransferTaskService.addDataTransferTask(buildDataTransferTaskRequestDto(responseDto,testTaskResponseDto));
                responseDto.setDataTransferTaskPkId(transferTaskPkId);
                dataAnalysisService.modifyById(scriptTestDataAnalysisConverter.toScriptTestDataAnalysisRequestDto(responseDto));
            }
        } catch (Exception e){
            log.error("脚本测试:数据同步（添加数据迁移任务失败）: {}", e.getMessage(), e);
            throw new RuntimeException("脚本测试:数据同步（添加数据迁移任务失败）"+e.getMessage());
        }
    }
    /**
     * @Method buildDataAnalysisRequestDto <br>
     * @Param
     * @Param pkId <br>
     * @Return com.hex.ds.hdtp.core.app.script.test.dto.request.ScriptTestDataAnalysisRequestDto <br>
     * @Description 查询数据分析结果dto<br>
     * @Author jian.qiao<br>
     * @Date 2023/10/27 18:36 <br>
     * @Version V1.0<br>
     */
    public ScriptTestDataAnalysisRequestDto buildDataAnalysisRequestDto(String pkId) {
        ScriptTestDataAnalysisRequestDto requestDto = new ScriptTestDataAnalysisRequestDto();
        requestDto.setTestScriptTaskPkId(pkId);
        requestDto.setContrastAnalysisResult(ScriptDataAnalysisResultEnum.DATA_COUNT_FAIL.getName());
        return requestDto;
    }

    /**
     * @Method buildDataTransferTaskRequestDto <br>
     * @Param
     * @Param responseDto
     * @Param testTaskResponseDto <br>
     * @Return com.hex.ds.hdtp.core.app.data.transfer.dto.request.DataTransferTaskRequestDto <br>
     * @Description 数据迁移dto<br>
     * @Author jian.qiao<br>
     * @Date 2023/10/27 18:36 <br>
     * @Version V1.0<br>
     */
    public DataTransferTaskRequestDto buildDataTransferTaskRequestDto(ScriptTestDataAnalysisResponseDto responseDto,ScriptDataTestTaskResponseDto testTaskResponseDto){
        DataTransferTaskRequestDto transferTaskRequestDto = new DataTransferTaskRequestDto();
        List<DataTransferListRequestDto> dataTransferListRequestDtoList = new ArrayList<>();
        dataTransferListRequestDtoList.add(buildDataTransferListRequestDto(responseDto));
        transferTaskRequestDto.setTableList(dataTransferListRequestDtoList);
        String taskName = "脚本测试-".concat(testTaskResponseDto.getTaskName()).concat("-").concat(responseDto.getScriptName()).concat("-")
                .concat(responseDto.getSourceTableName()).concat("-").concat(String.valueOf(System.currentTimeMillis()));
        transferTaskRequestDto.setTaskName(taskName);
        transferTaskRequestDto.setDataSyncType(testTaskResponseDto.getDataSyncType());
        transferTaskRequestDto.setIsDataAnalysis("N");
        transferTaskRequestDto.setStatus("PROCESSING");
        transferTaskRequestDto.setTotal(1);
        transferTaskRequestDto.setSuccessCount(0);
        transferTaskRequestDto.setFailCount(0);
        transferTaskRequestDto.setDataTransferType("Jdbc");
        transferTaskRequestDto.setTransferType(DataTransferTypeEnum.EXPAND_NUM.getValue());
        return transferTaskRequestDto;
    }

    /**
     * @Method buildDataTransferListRequestDto <br>
     * @Param
     * @Param responseDto <br>
     * @Return com.hex.ds.hdtp.core.app.data.transfer.dto.request.DataTransferListRequestDto <br>
     * @Description 数据迁移清单dto<br>
     * @Author jian.qiao<br>
     * @Date 2023/10/27 18:36 <br>
     * @Version V1.0<br>
     */
    public DataTransferListRequestDto buildDataTransferListRequestDto(ScriptTestDataAnalysisResponseDto responseDto){
        ScriptDataTestListResponseDto dataTestListResponseDto = dataTestListService.queryById(responseDto.getTestScriptListPkId());
        ScriptConvertTargetListResponseDto targetListResponseDto = convertTargetListService.queryById(dataTestListResponseDto.getScriptConvertListPkId());
        //数据源编码
        SourceInfoPo sourceConInfo = sourceInfoService.queryBySourceCode(targetListResponseDto.getSourceConnCode());
        SourceInfoPo targetConInfo = sourceInfoService.queryBySourceCode(targetListResponseDto.getTargetConnCode());
        DataTransferListRequestDto  requestDto = new DataTransferListRequestDto();
        requestDto.setSourceConnPkId(sourceConInfo.getPkId());
        requestDto.setTargetConnPkId(targetConInfo.getPkId());
        List<String> sourceTableStr = StrSpliter.split(responseDto.getSourceTableName(), ".",0, true,true);
        List<String> targetTableStr = StrSpliter.split(responseDto.getTargetTableName(), ".",0, true,true);
        requestDto.setSourceDatabaseName(CollUtil.getFirst(sourceTableStr));
        requestDto.setSourceTableName(CollUtil.getLast(sourceTableStr));
        requestDto.setTargetDatabaseName(CollUtil.getFirst(targetTableStr));
        requestDto.setTargetTableName(CollUtil.getLast(targetTableStr));
        TableTransferListResponseDto tableTransferListResponseDto
                = tableTransferListService.queryLatestTransferTableByTarget(CollUtil.getFirst(targetTableStr), CollUtil.getLast(targetTableStr), targetConInfo.getPkId());
        requestDto.setTableTransferListPkId(tableTransferListResponseDto.getPkId());
        return requestDto;
    }
}
